using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Net;

namespace MarcoBarzaghi.Diagnostics
{
    public class UpdTraceListener: TraceListener 
    {
        IPEndPoint endPoint;

        /// <summary>
        /// Initializes a new instance of the <see cref="T:UpdTraceListener"/> class.
        /// </summary>
        /// <param name="initializeData">The initialize data.</param>
        public UpdTraceListener(string initializeData)
        {
            try
            {
                IPAddress addressGroup = null;
                int groupPort = 0;

                string[] arguments = initializeData.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string argument in arguments)
                {
                    string[] items = argument.Split(new char[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries);
                    string name = items[0];
                    string value = items.Length > 1 ? items[1] : string.Empty;

                    switch (name)
                    {
                        case "ip":
                            addressGroup = IPAddress.Parse(value);
                            break;
                        case "port":
                            groupPort = int.Parse(value);
                            break;
                    }
                }

                if (addressGroup == null || groupPort == 0)
                    throw new ArgumentException(
                        "ip or port have not valid values.",
                        "initializeData");

                endPoint = new IPEndPoint(addressGroup, groupPort);
            }
            catch(Exception e)
            {
                throw new ArgumentException(
                    "UpdTraceListener: Invalid or malformed initialize data (ip=<ip>;port=<port>;).", 
                    "initializeData", e);
            }
        }

        /// <summary>
        /// When overridden in a derived class, writes the specified message to the listener you create in the derived class.
        /// </summary>
        /// <param name="message">A message to write.</param>
        public override void Write(string message)
        {
            byte[] data = Encoding.Default.GetBytes(message);
            UdpHelper.SendToMulticastGroup(endPoint, data);
        }

        /// <summary>
        /// When overridden in a derived class, writes a message to the listener you create in the derived class, followed by a line terminator.
        /// </summary>
        /// <param name="message">A message to write.</param>
        public override void WriteLine(string message)
        {
            string new_message = message + Environment.NewLine;
            Write(new_message);
        }
    }
}
